// 获取DOM元素
const loginForm = document.getElementById('loginForm');
const usernameInput = document.getElementById('username');
const passwordInput = document.getElementById('password');
const usernameError = document.getElementById('usernameError');
const passwordError = document.getElementById('passwordError');
const messageDiv = document.getElementById('message');
const loginBtn = document.getElementById('loginBtn');
const btnText = loginBtn.querySelector('.btn-text');
const loadingSpinner = loginBtn.querySelector('.loading-spinner');

// 输入验证函数
function validateUsername(username) {
    if (!username.trim()) {
        return '用户名不能为空';
    }
    if (username.length < 3) {
        return '用户名至少3个字符';
    }
    if (username.length > 20) {
        return '用户名不能超过20个字符';
    }
    return '';
}

function validatePassword(password) {
    if (!password) {
        return '密码不能为空';
    }
    if (password.length < 6) {
        return '密码至少6个字符';
    }
    return '';
}

// 实时验证
usernameInput.addEventListener('input', function() {
    const error = validateUsername(this.value);
    usernameError.textContent = error;
    this.classList.toggle('error', !!error);
});

passwordInput.addEventListener('input', function() {
    const error = validatePassword(this.value);
    passwordError.textContent = error;
    this.classList.toggle('error', !!error);
});

// 显示消息
function showMessage(text, type) {
    messageDiv.textContent = text;
    messageDiv.className = `message ${type}`;
    messageDiv.style.display = 'block';
    
    setTimeout(() => {
        messageDiv.style.display = 'none';
    }, 3000);
}

// 设置加载状态
function setLoading(isLoading) {
    if (isLoading) {
        loginBtn.disabled = true;
        btnText.style.display = 'none';
        loadingSpinner.style.display = 'inline-block';
    } else {
        loginBtn.disabled = false;
        btnText.style.display = 'inline-block';
        loadingSpinner.style.display = 'none';
    }
}

// 处理表单提交
loginForm.addEventListener('submit', async function(e) {
    e.preventDefault();
    
    // 清除之前的消息
    messageDiv.style.display = 'none';
    
    // 获取输入值
    const username = usernameInput.value.trim();
    const password = passwordInput.value;
    
    // 验证输入
    const usernameErrorText = validateUsername(username);
    const passwordErrorText = validatePassword(password);
    
    if (usernameErrorText || passwordErrorText) {
        usernameError.textContent = usernameErrorText;
        passwordError.textContent = passwordErrorText;
        usernameInput.classList.toggle('error', !!usernameErrorText);
        passwordInput.classList.toggle('error', !!passwordErrorText);
        return;
    }
    
    // 设置加载状态
    setLoading(true);
    
    try {
        // 模拟API调用（实际项目中可以替换为真实的API调用）
        const response = await fetch('http://localhost:3000/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ username, password })
        });
        
        const data = await response.json();
        
        if (response.ok) {
            showMessage('登录成功！正在跳转...', 'success');
            // 这里可以添加跳转逻辑
            setTimeout(() => {
                // window.location.href = '/dashboard';
            }, 1500);
        } else {
            showMessage(data.message || '登录失败，请重试', 'error');
        }
    } catch (error) {
        console.error('登录请求失败:', error);
        showMessage('网络错误，请稍后重试', 'error');
    } finally {
        setLoading(false);
    }
});

// 回车键提交
usernameInput.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        passwordInput.focus();
    }
});

passwordInput.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        loginForm.dispatchEvent(new Event('submit'));
    }
});
